<?php

namespace App\Console\Commands;

use App\Model\Business\Schedule;
use App\Model\Business\ScheduleStuden;
use App\Model\Foundation\Student;
use App\Model\Foundation\Teacher;
use App\Model\System\Notice;
use Illuminate\Console\Command;
use App\Model\System\NoticeConfig;


/**
 * 每分钟运行一次
 *
 * Class ScanBefore
 * @package App\Console\Commands
 */
class ScanBefore extends Command
{
    /**
     * 如果DB用时间戳，设置为1，datetime，设置为0
     */
    const  isStemp = 0;

    protected $signature = 'Notice:Before';

    protected $description = 'message scanner';

    public function __construct()
    {
        parent::__construct();
    }


    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        echo "Start: \n";

        try{
            #获取当前时间戳
            $now = time();

            #读取需要发送通知的用户
            $items = $this->getNoticeConfig();
            if(empty($items)){
                echo "nothing to do. \n";
            }else{
                #检测每个用户
                foreach ($items as $item){
                    $mins = $item['ahead'];
                    #获取某用户近期的排课
                    $sids = $this->getUserSchedules($item['uid'],$item['utype']);
                    foreach($sids as $sid){
                        $schedule = Schedule::where('scheduleid',$sid)->first();
                        $scnds = $schedule['begintime'];
                        if(!self::isStemp){
                            $scnds = strtotime($schedule['begintime']);
                        }
                        #间隔符合用户的配置，生产消息
                        $redutions = $scnds - $now;
                        if((floor($redutions/60)==$mins) or ceil($redutions/60)==$mins){
                            $this->makeMessage($item['uid'], $sids, $item['utype']);
                        }
                    }
                }
            }
        }catch (\Exception $e){
            echo $e->getMessage();
            echo "\n";
        }

        echo "down. \n";
        return true;
    }


    /**
     * 计算接下来的时间 now ～ 12小时
     *
     * @return array
     */
    protected function getTheDuration()
    {
        static $set = 0, $start = null, $end = null;
        if(!$set){
            $set = 1;
            $next = time();
            if(self::isStemp){
                $start = strtotime(date('Y-m-d', $next));
                $end =  strtotime(date('Y-m-d', $next+43200));
            }else{
                $start = date('Y-m-d H:i:s', $next);
                $end = date('Y-m-d H:i:s', $next+43200);
            }
        }
        return [$start, $end];
    }


    /**
     * 获取规定时间段内段排课
     */
    protected function getDurationSchedules()
    {
        static $schedules = [];

        if(empty($schedules)){
            list($start, $end) = $this->getTheDuration();
            $schedules = Schedule::where('begintime', '>=', $start)
                ->where('endtime', '<=', $end)
                ->pluck('scheduleid')
                ->toarray();
        }
        return $schedules;
    }

//    /**
//     * 检查学生课节数
//     * @param $studentuid
//     */
//    protected function getStudentSchedules($studentuid)
//    {
//        $schedules = $this->getDurationSchedules();
//        $sids = array_keys($schedules);
//        $mySids = ScheduleStuden::whereIn('scheduleid', $sids)
//            ->where('studentuid', $studentuid)
//            ->pluck('scheduleids')
//            ->toarray();
//        return $mySids;
//    }

    /**
     * 检查用户课节数
     * @param $studentuid
     */
    protected function getUserSchedules($uid,$type)
    {
        $sids = $this->getDurationSchedules();
        if($type == 1){
            $mySids = Schedule::whereIn('scheduleid',$sids)
                ->where('teacheruid',$uid)
                ->pluck('scheduleid')
                ->toarray();
        }else{
            $mySids = ScheduleStuden::whereIn('scheduleid', $sids)
                ->where('studentuid', $uid)
                ->pluck('scheduleid')
                ->toarray();
        }

        return $mySids;
    }

    /**
     * 时间段
     * @return false|string
     */
    protected function now()
    {
        # 720 分钟，12小时
        return 720;
    }


    /**
     * 获取本次需要提醒的学生
     */
    protected function getNoticeConfig()
    {
        $now = $this->now();
        $items = NoticeConfig::where('ahead', '<=', $now)->where('ahead', '>', 0)
            ->where('ntype', 1)
            ->get()
            ->toarray();
        return $items;
    }


    /**
     * 把消息记录到消息库
     */
    protected function makeMessage($uid, $sids ,$type)
    {
        $msg = ['jsonable'=>'1', 'to'=>'','title'=>'上课提醒','body'=>""];
        if($type == 1){
            $user = Teacher::where('teacheruid', $uid)->first();
            $username = $user->lastname;
            $userid = $user->userid;
        }else{
            $user = Student::where('studentuid', $uid)->first();
            $username = $user->name;
            $userid = $user->userid;
        }


        $schedules = Schedule::find($sids);

        foreach ($schedules as $item){
            $obj['username'] = $username;
            $obj['coursename'] = $item->name;
            if(self::isStemp){
                $obj['date'] = date('Y-m-d H:i:s', $item->begintime);
            }else{
                $obj['date'] = $item->begintime;
            }
            $obj['remark'] = '';

            # 存储
            $msg['to'] = $userid;
            $msg['body'] = json_encode($obj,JSON_UNESCAPED_UNICODE);
            $notice = new Notice($msg);
            $notice->save();
        }
    }



    /**
     * 把消息记录到消息库
     */
    protected function _makeMessage($studentuid, $sids)
    {
        $msg = ['jsonable'=>'1', 'to'=>'','title'=>'上课提醒','body'=>"你的课程即将开课，请准时参加。"];
        $userids = Student::where('studentuid', $studentuid)->pluck('userid')->toarray();
        foreach ($userids as $uid){
            $msg['to'] = $uid;
            $notice = new Notice($msg);
            $notice->save();
        }
    }


}
